package com.bodu.core.exception.handler;

import cn.hutool.json.JSONUtil;
import com.bodu.core.entity.result.Result;
import com.bodu.core.exception.custom.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 *
 * @author Administrator
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 查询数据异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result searchExceptionHandler(HttpServletRequest req, Exception e) {
        String json = JSONUtil.toJsonStr(req.getParameterMap());
        e.printStackTrace();
        if (e instanceof SearchException) {
            return Result.fail("查询数据失败>>>" + e.getMessage() + "\n" + json);
        } else if (e instanceof SaveException) {
            return Result.fail("保存数据失败>>>" + e.getMessage() + "\n" + json);
        } else if (e instanceof UpdateException) {
            return Result.fail("更新数据失败>>>" + e.getMessage() + "\n" + json);
        } else if (e instanceof DeleteException) {
            return Result.fail("删除数据失败>>>" + e.getMessage() + "\n" + json);
        } else if (e instanceof ListException) {
            return Result.fail("查询数据失败>>>" + e.getMessage() + "\n" + json);
        } else if (e instanceof ListCountException) {
            return Result.fail("查询统计数据失败>>>" + e.getMessage() + "\n" + json);
        } else if (e instanceof PageException) {
            return Result.fail("查询分页数据失败>>>" + e.getMessage() + "\n" + json);
        }
        log.error("发生[查询数据]异常！原因是：{}", e.getMessage() + "\n" + json);
        return Result.fail( e.getMessage() + "\n" + json);
    }
}
